package org.algorithm.biubiu.wheel_1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;

/**
 * @author jiazhaoxin
 * @Date 2022/2/13
 * @Desc {https://leetcode-cn.com/problems/add-two-numbers/}
 */
public class 链表相加 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null&&l2!=null){
            return l2;
        }
        if(l1!=null&&l2==null){
            return l1;
        }
        int carry = 0;
        ListNode result =  new ListNode(-1);
        ListNode dummy =result;
        while(l1!=null&&l2!=null){
            int value = l1.val+l2.val+carry;
            carry = value/10;
            dummy.next = new ListNode(value%10);
            l1= l1.next;
            l2 = l2.next;
            dummy = dummy.next;
        }
        while(l1!=null){
            //sum
            int value = l1.val+carry;
            carry =  value/10;
            dummy.next = new ListNode(value%10);
            l1= l1.next;
            dummy = dummy.next;
        }
        while(l2 != null){
            //sum
            int value = l2.val+carry;
            carry =  value/10;
            dummy.next = new ListNode(value%10);
            l2= l2.next;
            dummy = dummy.next;
        }
        if(carry!=0){
            //sum;
            dummy.next = new ListNode(carry);

        }
        return result.next;
    }
}
